package com.netty.chatRoom.client;

import com.netty.chatRoom.message.*;
import com.netty.chatRoom.protocol.MessageCodecSharable;
import com.netty.chatRoom.protocol.ProcotolFrameDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
public class ChatClient {
    public static void main(String[] args) {
        NioEventLoopGroup group = new NioEventLoopGroup();
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        // 设置登录同步变量
        CountDownLatch WAIT_FOR_LOGIN = new CountDownLatch(1);
        // 设置登录是否成功线程变量
        AtomicBoolean LOGIN_FLAG=new AtomicBoolean(false);
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.handler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                nioSocketChannel.pipeline().addLast(new ProcotolFrameDecoder());
//                nioSocketChannel.pipeline().addLast(LOGGING_HANDLER);
                nioSocketChannel.pipeline().addLast(MESSAGE_CODEC);
                // 添加心跳检测
                nioSocketChannel.pipeline().addLast(new IdleStateHandler(0,3,0));
                nioSocketChannel.pipeline().addLast(new ChannelDuplexHandler(){
                    @Override
                    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                        if(evt instanceof IdleStateEvent){
                            IdleStateEvent event=(IdleStateEvent) evt;
                            if (event.state()==IdleState.WRITER_IDLE){
                                log.debug("心跳检测执行");
                                ctx.writeAndFlush(new PingMessage());
                            }
                        }
                        super.userEventTriggered(ctx, evt);
                    }
                });
                nioSocketChannel.pipeline().addLast(new SimpleChannelInboundHandler<LoginResponseMessage>() {
                    @Override
                    protected void channelRead0(ChannelHandlerContext channelHandlerContext, LoginResponseMessage loginResponseMessage) throws Exception {
                        log.debug("msg:{}",loginResponseMessage);
                        boolean success = loginResponseMessage.isSuccess();
                        LOGIN_FLAG.set(success);
                        WAIT_FOR_LOGIN.countDown();
                        System.out.println(loginResponseMessage.getReason());
                    }
                });
                nioSocketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        log.info("msg:{}",msg);
                        super.channelRead(ctx, msg);
                    }

                    @Override
                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                        // 客户端创建成功，显示登录造作
                        new Thread(()->{
                            Scanner scanner=new Scanner(System.in);
                            System.out.println("请输入用户名：");
                            String username=scanner.nextLine();
                            System.out.println("请输入登录密码：");
                            String password=scanner.nextLine();
                            LoginRequestMessage loginRequestMessage = new LoginRequestMessage(username, password);
                            // 发送登录请求消息给服务端
                            ctx.writeAndFlush(loginRequestMessage);
                            try {
                                WAIT_FOR_LOGIN.await();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            if (!LOGIN_FLAG.get()){
                                ctx.channel().close();
                                return;
                            }

                            while (true){
                                // 登录成功命令输入逻辑
                                System.out.println("==================================");
                                System.out.println("send [username] [content]");
                                System.out.println("gsend [group name] [content]");
                                System.out.println("gcreate [group name] [m1,m2,m3...]");
                                System.out.println("gmembers [group name]");
                                System.out.println("gjoin [group name]");
                                System.out.println("gquit [group name]");
                                System.out.println("quit");
                                System.out.println("==================================");
                                String command = scanner.nextLine();
                                // 对命令进行拆分
                                String[] call = command.split(" ");
                                switch (call[0]){
                                    case "send":
                                        ctx.writeAndFlush(new ChatRequestMessage(username,call[1],call[2]));
                                        break;
                                    case "gsend":
                                        ctx.writeAndFlush(new GroupChatRequestMessage(username,call[1],call[2]));
                                        break;
                                    case "gcreate":
                                        ctx.writeAndFlush(new GroupCreateRequestMessage(username,call[1], new HashSet<String>(Arrays.asList(call[2].split(",")))));
                                        break;
                                    case "gmembers":
                                        ctx.writeAndFlush(new GroupMembersRequestMessage(call[1]));
                                        break;
                                    case "gjoin":
                                        ctx.writeAndFlush(new GroupJoinRequestMessage(username,call[1]));
                                        break;
                                    case "gquit":
                                        ctx.writeAndFlush(new GroupQuitRequestMessage(username,call[1]));
                                        break;
                                    case "quit":
                                        ctx.channel().close();
                                        return;
                                    default:
                                        System.out.println("【"+call[0]+"】是无效命令！");
                                        break;
                                }
                            }
                        },"login in").start();
                    }
                });
            }
        });
        ChannelFuture conFuture = bootstrap.connect(new InetSocketAddress("localhost", 8080));
        conFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                // 成功建立链接
                channelFuture.channel().closeFuture().addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture channelFuture) throws Exception {
                        group.shutdownGracefully();
                        log.debug("【{}】连接已关闭",this);
                    }
                });
            }
        });
    }
}
